<template>
	<!-- m -->
	<view class="goods-box" @tap="click">
		<view class="img-box"><image class="goods-img" lazy-load fade-show :src="image" mode="aspectFill"></image></view>
		<view class="goods-bottom u-p-14" :style="type ? 'background-image: url(' + $IMG_URL + typeMap[type].goodsBg + ')' : ''">
			<view class="title u-ellipsis-2 u-m-b-10">
				<view class=" sm cu-tag radius title-tag u-m-r-10" :style="{ backgroundColor: typeMap[type].tagBg, color: '#fff' }" v-if="type">{{ typeMap[type].text }}</view>
				{{ title }}
			</view>
			<view class="rongqis u-flex">
				<view class=" line-red sm radius" v-for="(item, index) in tag_list" :key="index">{{ item }}</view>
			</view>
			<slot name="cardBottom">
				<view class="u-flex u-col-center u-row-between">
					<view class="price-box">
						<view class="price u-flex u-m-b-10" :class="(toptitle=='限时秒杀'||toptitle=='折上返券'||toptitle=='预售专区')||isCart(detail.id)?'u-row-between':''">
              <view class="moneys" v-if="discount_price">{{ discount_price }}</view>
              <view class="moneys" v-else>{{ price }}</view>
<!--              <view class="num-step" v-if="(toptitle!='限时秒杀'&&toptitle!='折上返券'&&toptitle!='预售专区')&&isCart(detail.id)&&!detail.is_sku">-->
<!--                <u-number-box-->
<!--                    v-if="isshowjishuqi"-->
<!--                    :value="checkCart[detail.id].num"-->
<!--                    :min="0"-->
<!--                    :step="1"-->
<!--                    :max="detail.sku_price[0].stock"-->
<!--                    disabled-input-->
<!--                    @minus="minus($event, detail.sku_price[0])"-->
<!--                    @plus="plus($event, detail.sku_price[0])"-->
<!--                ></u-number-box>-->
<!--              </view>-->
              <view class="cart-box" v-if="toptitle=='限时秒杀'||toptitle=='折上返券'||toptitle=='预售专区'">
                <button class="u-reset-button buy-btn"  @tap.stop="click" v-if="toptitle=='限时秒杀'">去抢购</button>
                <button class="u-reset-button yushou-btn" @tap.stop="click"  v-if="toptitle=='预售专区'">提醒</button>
                <button class="u-reset-button dazhe-btn" @tap.stop="click"  v-if="toptitle=='折上返券'">立即抢</button>
              </view>
            </view>
						<view class="origin-price">{{ zeng_text }}</view>
					</view>
          <!-- 加入购物车 -->
          <view class="cart-box" v-if="toptitle!='限时秒杀'&&toptitle!='折上返券'&&toptitle!='预售专区'">
            <view class="">
              <button class="u-reset-button cart-btn u-flex u-col-center u-row-center" @tap.stop="click">
                <view class="u-iconfont uicon-shopping-cart-fill" style="color: #fff;"></view>
              </button>
            </view>
<!--            <view v-if="detail.activity_type!='seckill'&&detail.goods_type=='1'">-->
<!--              &lt;!&ndash; 单规格  @tap.stop="addCart(detail.sku_price[0])"&ndash;&gt;-->
<!--              <view class="" v-if="!detail.is_sku">-->
<!--                <button class="u-reset-button cart-btn u-flex u-col-center u-row-center" v-if="!isCart(detail.id)" @tap.stop="click">-->
<!--                  <view class="u-iconfont uicon-shopping-cart-fill" style="color: #fff;"></view>-->
<!--                </button>-->
<!--              </view>-->
<!--              &lt;!&ndash; 多规格  @tap.stop="selSku(detail)"&ndash;&gt;-->
<!--              <button class="u-reset-button item-btn cart-btn  u-flex u-col-center u-row-center" @tap.stop="click" v-else>-->
<!--                <view class="u-iconfont uicon-shopping-cart-fill" style="color: #fff;"></view>-->
<!--              </button>-->
<!--            </view>-->
<!--            <view v-else>-->
<!--              <button class="u-reset-button item-btn cart-btn  u-flex u-col-center u-row-center" @tap.stop="click">-->
<!--                <view class="u-iconfont uicon-shopping-cart-fill" style="color: #fff;"></view>-->
<!--              </button>-->
<!--            </view>-->
          </view>

        </view>
			</slot>
		</view>
    <u-toast ref="submitAudit"></u-toast>
		<!-- 规格弹窗 -->
		<shopro-sku v-if="showSku && goodsInfo.id" v-model="showSku" :goodsInfo="goodsInfo" buyType="cart"></shopro-sku>
	</view>
</template>

<script>
/**
 *shoproGoodsCard - 商品列表卡片
 * @property {Object} detail - 商品详情
 * @property {String} type - 商品类型
 * @property {String} image - 商品图片
 * @property {String} title - 商品标题
 * @property {String} subtitle - 商品副标题
 * @property {String | Number} price - 商品价格
 * @property {String | Number} discount_price - 商品优惠券原价
 * @property {String | Number} originPrice - 商品原价
 * @property {String | Number} sales - 商品销量
 * @property {Array} tagTextList - 活动标签
 * @event {Function} click 商品被点击
 */
import { mapMutations, mapActions, mapState, mapGetters } from 'vuex';
export default {
	components: {},
	data() {
		return {
			maxStep: 999999,
			showSku: false,
			goodsInfo: {}, //商品详情
			typeMap: {
				seckill: {
					text: '秒杀',
					tagBg: '#FF5854',
				},
				groupon: {
					text: '拼团',
					tagBg: '#FE832A',
				}
			},
      isshowjishuqi:false
		};
	},
	computed: {
		...mapGetters(['cartList', 'checkCart'])
	},
	props: {
		detail: {
			type: Object,
			default: () => {
				return {};
			}
		},
		type: {
			type: [String,null],
			default: ''
		},
		image: {
			type: String,
			default: ''
		},
		title: {
			type: String,
			default: ''
		},
    toptitle:{
      type: String,
      default: ''
    },
		price: {
			type: [String, Number],
			default: ''
		},
    discount_price: {
      type: [String, Number],
      default: ''
    },
		originPrice: {
			type: [String, Number],
			default: ''
		},
    tag_list: {
      type: Array,
      default: []
    },
    zeng_text: {
      type: [String, Number],
      default: ''
    },
		sales: {
			type: [String, Number],
			default: ''
		},
	},
	methods: {
		...mapActions(['getCartList','changeCartList', 'addCartGoods']),
		//点击商品
		click() {
			this.$emit('click');
		},

		// 检测是否为购物车商品
		isCart(id) {
      this.isshowjishuqi = true;
   		return Object.keys(this.checkCart).includes(id + '');
		},

		// 检测商品在购物车中的下标
		checkGoodsIndex(id) {
			let cIndex = 0;
      console.log("======this.cartList",this.cartList)
			this.cartList.forEach((item, index) => {
				if (id == item.goods_id) {
					cIndex = index;
				}
			});
			return cIndex;
		},
    // 到达最小值
    minus(e, sku) {
      const that = this;
      if(e.value < 1){
        let cartGoodId = 0;
        let goods = []
        goods = that.cartList.filter(item => item.goods_id === that.detail.id)
        cartGoodId = that.cartList.filter(item => item.goods_id === that.detail.id)[0].id;
        uni.showModal({
          title: '删除提示',
          confirmColor: '#fc5351',
          content: `是否确认从购物车中删除此商品?`,
          success: (res) => {
            res.confirm && that.changeCartList({ ids: [cartGoodId], art: 'delete' });
            if(res.cancel){
              this.isshowjishuqi = false;
              console.log(" this.isshowjishuqi =========", this.isshowjishuqi )
              return
              setTimeout(()=>{
                this.isshowjishuqi = true
              },100)
            }
          }
        });
      }else{
        that.onChangeNum(e, sku)
      }
    },
    // 增加
    plus(e, sku) {
      console.log("==========e, sku",e, sku)
      // return
      if (e.value >= sku.stock) {
        this.$u.toast('库存不足');
        return;
      }else if (this.detail.activity_type === 'seckill' || this.detail.activity_type === 'groupon') {
        let rules = this.detail.activity.rules;
        if (rules.limit_buy != 0 && e.value >= rules.limit_buy) {
          this.$u.toast('本次活动最多购买' + rules.limit_buy + '件');
          return;
        }
      }else{
      this.onChangeNum(e, sku);
      this.isshowjishuqi = true;
      }
    },
		// 更改商品数
		async onChangeNum(e, sku) {
		  var that = this;
      that.maxStep = sku.stock;
      let gIndex = that.checkGoodsIndex(sku.goods_id);
      that.$set(that.cartList[gIndex], 'goods_num', +e.value);
      console.log("=======e.value != that.checkCart[sku.goods_id].num",e.value != this.checkCart[sku.goods_id].num,Math.abs(e.value - that.checkCart[sku.goods_id].num) == '1',e.value,that.checkCart[sku.goods_id].num)
      if (e.value != this.checkCart[sku.goods_id].num) {
        uni.showLoading({
          mask: true
        });
        await that.changeCartList({
          ids: [that.checkCart[sku.goods_id].cartOrderId],
          goodsNum: +e.value,
          art: 'change'
        });
        await uni.hideLoading();
      }
		},
		// 添加购物车,多规格
		async selSku(info) {
			// if (this.detail.activity_type) {
			// 	this.$Router.push({ path: '/pages/goods/new_detail', query: { id: this.detail.id } });
			// 	return;
			// }
			this.goodsInfo = {};
			this.getGoodsDetail(info.id);
			this.showSku = true;
		},

		// 商品详情
		getGoodsDetail(id) {
			let that = this;
			that.$https('goods.getShopDetail', {
				id: id
			}).then(res => {
				if (res.code === 1) {
					that.goodsInfo = res.data;
				}
			});
		},

		// 加入购物车
		addCart(sku) {
		  if(!uni.getStorageSync("token")){
        this.getCartList();
      }
			if (sku.stock <= 0) {
				this.$u.toast('库存不足');
				return;
			}
			if (this.detail.activity_type) {
				this.$Router.push({ path: '/pages/goods/new_detail', query: { id: this.detail.id } });
				return;
			}
			let confirmGoodsList = {
				list: [
					{
						goods_id: sku.goods_id,
						goods_num: 1,
						sku_price_id: sku.id,
						goods_price: sku.price
					}
				],
				from: 'goods'
			};
			this.addCartGoods(confirmGoodsList).then(res => {
				if (res.code === 1) {
          let options = {
            type:"default",
            icon:'checkmark-circle',
            back: false,
            title:'成功加入购物车'
          };
          console.log("============thatoptions",options,this.$refs.submitAudit)
          this.$refs.submitAudit.show(options);
				}
			});
		}
	},
  created(){
    // console.log("=====is_sku",this.detail.is_sku,this.detail)
  }
};
</script>

<style lang="scss">
.goods-box {
  width: 100%;
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	.goods-bottom {
		background-size: 100% 100%;
		background-position: bottom center;
		background-repeat: no-repeat;
	}
	.img-box {
		overflow: hidden;
		position: relative;
		background-color: #fff;
		border-radius: 6rpx;
		.goods-img {
      width: 100%;
      height: 260rpx;
      background-color: #f5f5f5;
      border-radius: 20rpx;
		}
	}

	.title {
		vertical-align: center;
		font-size: 28rpx;
		font-weight: bold;
		line-height: 40rpx;
		color: #333333;
		padding-top: 6rpx;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
		.title-tag {
			position: relative;
			top: -6rpx;
		}
	}
	.sub-title {
		font-size: 24rpx;
		font-weight: 400;
		color: #999999;
	}
	.price-box {
    width: 100%;
		.price {
      .moneys{
        font-size: 30rpx;
        color: #ff3000;
        font-weight: 600;
        &::before {
          content: '￥';
          font-size: 24rpx;
        }
      }
		}
		.origin-price {
			font-size: 24rpx;
			font-weight: 400;
			color: #c4c4c4;
		}
		.sales-box {
			font-size: 18rpx;

			font-weight: 400;
			color: #c4c4c4;
			line-height: 20rpx;
		}
	}
	// 购物车
  // 购物车
  .cart-box {
    .cart-btn {
      width: 54rpx;
      height: 54rpx;
      border-radius: 50%;
      padding: 0;
      background: rgb(252, 83, 81);
      //background: linear-gradient(90deg, #e9b461, #eecc89);
    }
    .buy-btn {
      width: 120rpx;
      line-height: 50rpx;
      background: rgb(252, 83, 81);
      //background: linear-gradient(90deg, #e9b461, #eecc89);
      border-radius: 25rpx;
      font-size: 24rpx;
      font-weight: 500;
      color: #ffffff;
    }
  }
}
.rongqis{
 flex-wrap: wrap;
}
.line-red{
  padding: 4rpx 8rpx;
  margin-bottom: 10rpx;
  line-height: 30rpx;
  background-color: #FFF0E4;
  text-align: center;
  font-size: 20rpx;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: 500;
  margin-right: 6rpx;
  color: #ff9900!important;
  border: none!important;
}

.buy-btn {
  width: 120rpx;
  line-height: 50rpx;
  background:#ed3c30;
  border-radius: 25rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #ffffff;
  margin: 0;
}
.yushou-btn{
  width: 120rpx;
  line-height: 50rpx;
  background: #3A8EFD;
  border-radius: 25rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #ffffff;
  margin: 0;
}
.dazhe-btn{
  width: 120rpx;
  line-height: 50rpx;
  border-radius: 25rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #ffffff;
  margin: 0;
  background: linear-gradient(139deg, #F3B745 5%, #FF9E31 100%);
}
/deep/.num-step{
  border: 1rpx solid #D9D9D9;
  border-radius: 26rpx;
  overflow: hidden;
}
</style>
